from flask import Blueprint, request
from utils.response import success, error
import random
import requests
from datetime import datetime

# 创建蓝图
getOne_bp = Blueprint("getOne", __name__)

api_list = [
    {
        "id": "ONE",
        "api": "http://v3.wufazhuce.com:8000/api/channel/one/0/0",
        "fn": lambda data: {
            "content": data["data"]["content_list"][0]["forward"],
            "author": (
                data["data"]["content_list"][0]["author"]["user_name"]
                if data["data"]["content_list"][0].get("author")
                else (
                    data["data"]["content_list"][0]["text_author_info"][
                        "text_author_name"
                    ]
                    if data["data"]["content_list"][0].get("text_author_info")
                    else "佚名"
                )
            ),
        },
    },
    {
        "id": "金山词霸",
        "api": "http://open.iciba.com/dsapi/",
        "fn": lambda data: {
            "content": data["note"],
            "author": "佚名",
        },
    },
    {
        "id": "扇贝单词",
        "api": "https://apiv3.shanbay.com/weapps/dailyquote/quote",
        "fn": lambda data: {
            "content": data["translation"],
            "author": data.get("author", "佚名"),
        },
    },
    {
        "id": "一言",
        "api": "https://v1.hitokoto.cn/",
        "fn": lambda data: {
            "content": data["hitokoto"],
            "author": data.get("from", "佚名"),
        },
    },
    {
        "id": "今日诗词",
        "api": "https://v2.jinrishici.com/one.json",
        "fn": lambda data: {
            "content": data["data"]["content"],
            "author": data["data"]["origin"].get("author", "佚名"),
            "dynasty": data["data"]["origin"].get("dynasty", "未知"),
            "title": data["data"]["origin"].get("title", "无题"),
            "conten_all": data["data"]["origin"].get("content", ""),
        },
        "token": "cogDwgGDAXzg9UqmtDVPireUp2ocFPRN",
    },
]


def fetch_random_data():
    """
    随机选择一个 API，发送请求并处理数据
    """
    try:
        # 随机选择一个 API
        # selected_api = random.choice(api_list)
        selected_api = api_list[4]
        api_url = selected_api["api"]
        process_fn = selected_api["fn"]
        token = selected_api.get("token", "")
        if token:
            headers = {"Cookie": f"X-User-Token={token}"}
        else:
            headers = {}

        response = requests.get(api_url, headers=headers)
        print(f"response: {response}")
        response.raise_for_status()

        # 解析响应数据
        data = response.json()
        print(f"data: {data}")

        # 使用 fn 函数处理数据
        processed_data = process_fn(data)

        # 获取当天日期
        today = datetime.now().strftime("%Y-%m-%d")

        # 返回统一格式的结果
        return success(
            data={
                "time": today,
                "content": processed_data["content"],
                "author": processed_data["author"],
                "dynasty": processed_data.get("dynasty", ""),
                "title": processed_data.get("title", ""),
                "conten_all": processed_data.get("conten_all", ""),
            },
            message="获取成功",
        )

    except requests.exceptions.RequestException as e:
        return error(f"网络请求失败: {e}")
    except Exception as e:
        return error(f"发生错误: {e}")


@getOne_bp.route("/get-one", methods=["POST"])
def getOne_api():
    """
    获取随机数据的接口
    """
    # 检查请求头是否为 JSON
    if not request.is_json:
        return error(message="请求头 Content-Type 必须为 application/json")

    # 调用 fetch_random_data 并返回结果
    try:
        result = fetch_random_data()
        return result  # 确保返回结果
    except Exception as e:
        return error(message=f"获取数据失败: {e}")
